package com.heima.behavior.service;

import com.alibaba.fastjson.JSON;
import com.heima.common.cache.CacheService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.model.behavior.dtos.ReadBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author 大可
 * @date 2022/7/28 15:25
 */
@Service
@Slf4j
public class ApReadBehaviorServiceImpl implements ApReadBehaviorService {

    @Autowired
    private CacheService cacheService;

    @Override
    public ResponseResult readBehavior(ReadBehaviorDto dto) {
        //入参校验
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //用户登录校验
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        Long articleId = dto.getArticleId();
        Integer userId = user.getId();

        String o = (String) cacheService.hGet(BehaviorConstants.READ_BEHAVIOR + articleId, userId.toString());
        if (o == null) {
            ReadBehaviorDto readBehaviorDto = JSON.parseObject(o, ReadBehaviorDto.class);
            //获取文章阅读
            Short count = readBehaviorDto.getCount();
            Short currentCount = dto.getCount();
            short newCount = (short) (count + currentCount);
            dto.setCount(newCount);
        }
        //更新该用户对这篇文章的阅读数量
        cacheService.hPut(BehaviorConstants.READ_BEHAVIOR + articleId,userId.toString(),JSON.toJSONString(dto));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
